<?php

//就近 www.jiujin.me
global $_W, $_GPC;
$openid = m('user')->getOpenid();
$mem = m('member')->getMember($openid);
$agentid = $mem['id'];
$month=$_GPC['month'];
load()->func('file');
load()->func('tpl');
include_once '../addons/amouse_ecard/site.php';
$amouse_ecard= new Amouse_ecardModuleSite();
$op = empty($_GPC['op']) ? 'display' : $_GPC['op'];
if($op == 'display'){
if ($_W['isajax']) {
	$member = $this->model->getInfo($openid, array('total', 'ordercount0', 'ok'));
	$cansettle = $member['commission_ok'] > 0 && $member['commission_ok'] >= floatval($this->set['withdraw']);
	$commission_ok = $member['commission_ok'];
	$member['agentcount'] = number_format($member['agentcount'], 0);
	$member['ordercount0'] = number_format($member['ordercount0'], 0);
	$member['commission_ok'] = number_format($member['commission_ok'], 2);
	$member['commission_pay'] = number_format($member['commission_pay'], 2);
	$member['commission_total'] = number_format($member['commission_total'], 2);
	
	/*
	 *  gmm
	 *  功能：上级分销人
	 *  时间：2015年11月24日
	 */
	if($member['agentid']){
		$shangji = pdo_fetch('select nickname from ' . tablename('ewei_shop_member') . " where uniacid=:uniacid AND id =:id", array(':uniacid' => $_W['uniacid'],':id'=>$member['agentid']));
		$member['shangji'] = $shangji['nickname'];
	}
	
	if (mb_strlen($member['nickname'], 'utf-8') > 6) {
		$member['nickname'] = mb_substr($member['nickname'], 0, 6, 'utf-8');
	}
	$openselect = false;
	if ($this->set['select_goods'] == '1') {
		if (empty($member['agentselectgoods']) || $member['agentselectgoods'] == 2) {
			$openselect = true;
		}
	} else {
		if ($member['agentselectgoods'] == 2){
			$openselect = true;
		}
	}
	$this->set['openselect'] = $openselect;
	$level = $this->model->getLevel($openid);
        $info=pdo_fetch('select * from '.tablename('mc_members').'where uid=:uid and uniacid=:uniacid',array(':uniacid'=>$_W['uniacid'],':uid'=>$member['uid']));
	show_json(1, array('commission_ok' => $commission_ok, 'member' => $member, 'level' => $level, 'cansettle' => $cansettle, 'settlemoney' => number_format(floatval($this->set['withdraw']), 2), 'set' => $this->set,'gift'=>$info['gift'],'gold'=>$info['gold']));
}
//gmm 2015-12-21 大伙伴审核人数小圆点
if($mem['agentlevel'] == 1 || $mem['agentlevel'] == 2){		//战略或大伙伴
	$confirm_num = pdo_fetchcolumn('select count(*) from ' . tablename('ewei_shop_member') . " where uniacid = :uniacid and zhaomu = 1 and status = 0 and isagent = 1 and agentid = :agentid ",
			array(':uniacid' => $_W['uniacid'], ':agentid' => $mem['id']));
}else{
	$confirm_num = 0;
}

include $this->template('index');
}
//分享平台软文发展下线
//gwj 2016/10/12
if($op=="article"){
    $member = m('member')->getMember($openid);
     if($member['isShop']!=1){
     exit;
     }
    if($member['shoptype']==1 || $member['shoptype']==2 || $member['shoptype']==3){
    $list = pdo_fetchall("SELECT * FROM " . tablename('ewei_shop_article') . " WHERE uniacid=:uniacid and id>88 order by id desc", array(':uniacid' => $_W['uniacid']));
    include $this->template('article');
    }
}
if($op=="accounting"){
global $_W, $_GPC;
$openid = m('user')->getOpenid();
$member = $this->model->getInfo($openid, array('ordercount0'));
$agentLevel = $this->model->getLevel($openid);
$level = intval($this->set['level']);
$commissioncount = 0;
$status =3;
$condition = ' and o.status>=0';
if ($status != '') {
	$condition = ' and o.status=' . intval($status);
}
$orders = array();
$level1 = $member['level1'];
$level2 = $member['level2'];
$level3 = $member['level3'];
$ordercount = $member['ordercount0'];
if ($level >= 1) {
	$level1_memberids = pdo_fetchall('select id from ' . tablename('ewei_shop_member') . ' where uniacid=:uniacid and agentid=:agentid', array(':uniacid' => $_W['uniacid'], ':agentid' => $member['id']), 'id');
	$level1_orders = pdo_fetchall('select og.commission1,o.id,o.createtime,o.price from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . " where o.uniacid=:uniacid and o.agentid=:agentid {$condition} and og.status1>=0", array(':uniacid' => $_W['uniacid'], ':agentid' => $member['id']));
        //$level1_orders = pdo_fetchall('select og.commission1,o.id,o.createtime,o.price from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . " where o.uniacid=:uniacid and o.mid=:mid {$condition}", array(':uniacid' => $_W['uniacid'], ':mid' => $member['id']));
        //$ordercount = pdo_fetchall('select count(*) as count from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . " where o.uniacid=:uniacid and o.mid=:mid {$condition}", array(':uniacid' => $_W['uniacid'], ':mid' => $member['id']));
        $ordercount = pdo_fetchall('select count(*) as count from ' . tablename('ewei_shop_order') ."as o where o.uniacid=:uniacid and o.agentid=:agentid {$condition}", array(':uniacid' => $_W['uniacid'], ':agentid' => $member['id']));
        $ordercount=$ordercount[0]['count'];
        foreach ($level1_orders as $o) {
		if (empty($o['id'])) {
			continue;
		}
		$commission = iunserializer($o['commission1']);
		$commission_ok = isset($commission['level' . $agentLevel['id']]) ? $commission['level' . $agentLevel['id']] : $commission['default'];
		$hasorder = false;
		foreach ($orders as &$or) {
			if ($or['id'] == $o['id'] && $or['level'] == 1) {
				$or['commission'] += $commission_ok;
				$hasorder = true;
				break;
			}
		}
		unset($or);
		if (!$hasorder) {
			$orders[] = array('id' => $o['id'], 'commission' => $commission_ok, 'createtime' => $o['createtime'], 'level' => 1);
		}
		$commissioncount += $commission_ok;
	}
}
if ($level >= 2) {
	if ($level1 > 0) {
		$level2_orders = pdo_fetchall('select commission2 ,o.id,o.createtime,o.price   from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . " where o.uniacid=:uniacid and o.agentid in( " . implode(',', array_keys($member['level1_agentids'])) . ")  {$condition}  and og.status2>=0 ", array(':uniacid' => $_W['uniacid']));
		foreach ($level2_orders as $o) {
			if (empty($o['id'])) {
				continue;
			}
			$commission = iunserializer($o['commission2']);
			$commission_ok = isset($commission['level' . $agentLevel['id']]) ? $commission['level' . $agentLevel['id']] : $commission['default'];
			$hasorder = false;
			foreach ($orders as &$or) {
				if ($or['id'] == $o['id'] && $or['level'] == 2) {
					$or['commission'] += $commission_ok;
					$hasorder = true;
					break;
				}
			}
			unset($or);
			if (!$hasorder) {
				$orders[] = array('id' => $o['id'], 'commission' => $commission_ok, 'createtime' => $o['createtime'], 'level' => 2);
			}
			$commissioncount += $commission_ok;
		}
	}
}
if ($level >= 3) {
	if ($level2 > 0) {
		$level3_orders = pdo_fetchall('select commission3 ,o.id,o.createtime,o.price  from ' . tablename('ewei_shop_order_goods') . ' og ' . ' left join  ' . tablename('ewei_shop_order') . ' o on og.orderid=o.id ' . ' where o.uniacid=:uniacid and o.agentid in( ' . implode(',', array_keys($member['level2_agentids'])) . ")  {$condition} and og.status3>=0", array(':uniacid' => $_W['uniacid']));
		foreach ($level3_orders as $o) {
			if (empty($o['id'])) {
				continue;
			}
			$commission = iunserializer($o['commission3']);
			$commission_ok = isset($commission['level' . $agentLevel['id']]) ? $commission['level' . $agentLevel['id']] : $commission['default'];
			$hasorder = false;
			foreach ($orders as &$or) {
				if ($or['id'] == $o['id'] && $or['level'] == 3) {
					$or['commission'] += $commission_ok;
					$hasorder = true;
					break;
				}
			}
			unset($or);
			if (!$hasorder) {
				$orders[] = array('id' => $o['id'], 'commission' => $commission_ok, 'createtime' => $o['createtime'], 'level' => 3);
			}
			$commissioncount += $commission_ok;
		}
	}
}
usort($orders, 'sortByCreateTime');
$commissioncount = number_format($commissioncount, 2);
if(!empty($month)){
$year=date('Y',time());//获取年份
$firstday=$year."-".$month."-01";
$firsttime=strtotime($firstday);
$lastday =date('Y-m-d', strtotime("$firstday +1 month"));//当月的最后一天
$lasttime=strtotime($lastday); 
}else{
//当月的销售统计
$firstday =date('Y-m-01',time());//当月的第一天
$firsttime=strtotime($firstday);
$lastday =date('Y-m-d', strtotime("$firstday +1 month"));//当月的最后一天
$lasttime=strtotime($lastday);    
}
$ids=array();
foreach ($orders as $o) {
        $ids[$o['id']] = $o;
}
$total=0;
$list_order=array();
$totalmoney=0;
if($ids){
$total= pdo_fetchcolumn("select count(*) from " . tablename('ewei_shop_order') . "  where uniacid ={$_W['uniacid']} and paytime>$firsttime and paytime<$lasttime and id in ( " . implode(',', array_keys($ids)) . ") order by id desc");
$list_order= pdo_fetchall("select id,ordersn,finishtime,status,goodsprice from " . tablename('ewei_shop_order') . "  where uniacid ={$_W['uniacid']} and paytime>$firsttime and paytime<$lasttime and id in ( " . implode(',', array_keys($ids)) . ") order by id desc ");
foreach($list_order as $k=>$v){
    $totalmoney+=$v['goodsprice'];
}
}
if ($_W['isajax']) {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 20;
	$orders1 = array_slice($orders, ($pindex - 1) * $psize, $psize);
	$orderids = array();
	foreach ($orders1 as $o) {
		$orderids[$o['id']] = $o;
	}
	$list = array();
	if (!empty($orderids)) {
		$list = pdo_fetchall("select id,ordersn,finishtime,status,goodsprice,openid from " . tablename('ewei_shop_order') . "  where uniacid ={$_W['uniacid']} and paytime>$firsttime and paytime<$lasttime and id in ( " . implode(',', array_keys($orderids)) . ") order by id desc limit " . ($pindex - 1) * $psize . ',' . $psize);
                foreach ($list as &$row) {
                        $userinfo=pdo_fetch("select * from ".tablename('ewei_shop_member')."where uniacid=:uniacid and openid=:openid",array(':uniacid'=>$_W['uniacid'],':openid'=>$row['openid']));
                        $row['nickname']=$userinfo['nickname'];
			$row['commission'] = number_format($orderids[$row['id']]['commission'], 2);
			$row['finishtime'] = date('Y-m-d H:i:s', $row['finishtime']);
			if ($row['status'] == 0) {
				$row['status'] = '待付款';
			} else {
				if ($row['status'] == 1) {
					$row['status'] = '已付款';
				} else {
					if ($row['status'] == 2) {
						$row['status'] = '待收货';
					} else {
						if ($row['status'] == 3) {
							$row['status'] = '已完成';
						}
					}
				}
			}
			if ($orderids[$row['id']]['level'] == 1) {
				$row['level'] = '一';
			} else {
				if ($orderids[$row['id']]['level'] == 2) {
					$row['level'] = '二';
				} else {
					if ($orderids[$row['id']]['level'] == 3) {
						$row['level'] = '三';
					}
				}
			}
		}
		unset($row);
	}
	show_json(1, array('list' => $list, 'pagesize' => $psize));
}
include $this->template('accounting');
}
if($op=="month_search"){
include $this->template('month_search');
}
if($op=="fightgroups"){
    $id = intval($_GPC['id']);
    if(!empty($_GPC['data'])){
        $data=$_GPC['data'];
        $nowtime=time();
        $data['starttime']=strtotime($data['starttime']);
        $data['overtime']=strtotime($data['overtime']);
        $insert=array(
           'uniacid'=>$_W['uniacid'],
           'openid'=>$openid,
           'gname'=>$data['gname'],
           'fk_typeid'=>5,//默认商品分类
           'gnum'=>$data['gnum'],
            'groupnum'=>$data['groupnum'],
            'mprice'=>$data['mprice'],
            'gprice'=>$data['gprice'],
            'gprice_two'=>$data['gprice_two'],
            'oprice'=>$data['oprice'],
            'gdesc'=>$data['gdesc'],
            'gimg'=>$data['gimg'],
            'isshow'=>$data['isshow'],
            'salenum'=>$data['salenum'],
            'createtime'=>$nowtime,
            'endtime'=>$data['endtime'],
            'yunfei_id'=>4,//运费包邮
            'is_discount'=>1,
            'gdetaile'=>$data['gdetaile'],
            'starttime'=>$data['starttime'],
            'overtime'=>$data['overtime']
        );
        $images=explode(';',$data['img']);
        if (empty($id)) {
            $ret = pdo_insert('tg_goods', $insert);
            if (!empty($ret)) {
                    $goodsid = pdo_insertid();
            }
            if ($images && $goodsid){
                foreach ($images as $key => $value) {
                        if(!empty($images[$key])){
                        $data1 = array('thumb' => $images[$key], 'g_id' =>$goodsid);
                        pdo_insert('tg_goods_atlas', $data1);
                        }
                }
            }
        }else{
            if ($images){
                    pdo_delete('tg_goods_atlas', array('g_id' => $id));
                    foreach ($images as $key => $value) {
                           if(!empty($images[$key])){
                            $data2 = array('thumb' => $images[$key], 'g_id' => $id);
                            pdo_insert('tg_goods_atlas', $data2);
                           }
                    }
            }
	    $ret = pdo_update('tg_goods',$insert, array('id' => $id));
            $goodsid=$id;
        }
        show_json(1,array('goodsid'=>$goodsid));
    }
    if($id){
        $thisgoods = pdo_fetch("select * from " . tablename("tg_goods") . " WHERE id='{$id}'");
        $thisgoods['starttime']=date("Y-m-d H:i",$thisgoods['starttime']);
        $thisgoods['overtime']=date("Y-m-d H:i",$thisgoods['overtime']);
        $listt = pdo_fetchall("SELECT * FROM" . tablename('tg_goods_atlas') . "WHERE g_id = '{$id}' ");
        $piclist = array();
        if (is_array($listt)) {
            foreach ($listt as $p) {
                    $piclist[] = $p['thumb'];
            }
	}
    }
include $this->template('fightgroups'); 
}
if($op=="fightgroups_list"){
     $list=pdo_fetchall("select * from".tablename("tg_goods")." where uniacid=:uniacid and openid=:openid order by id desc ",array(":uniacid"=>$_W['uniacid'],":openid"=>$openid));
    foreach($list as $k=>$v){
    $list[$k]['starttime']=date("Y-m-d",$v['starttime']);
    $list[$k]['overtime']=date("Y-m-d",$v['overtime']);
    }
include $this->template('fightgroups_list'); 
}